package com.ruoyi.merchant.controller;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.merchant.domain.dto.*;
import com.ruoyi.merchant.domain.vo.MerchantDetailVO;
import com.ruoyi.merchant.domain.vo.PersonalInfoVO;
import com.ruoyi.merchant.domain.vo.UpdateStatusResponse;
import com.ruoyi.merchant.service.IMerchantAuthService;
import com.ruoyi.merchant.service.IMerchantService;
import com.ruoyi.merchant.service.MerchantProfileService;
import com.ruoyi.merchant.utils.AliOssUtil;
import com.ruoyi.merchant.utils.MerchantSecurityUtils;
import com.ruoyi.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;

import static com.ruoyi.common.core.domain.AjaxResult.error;
import static com.ruoyi.common.core.domain.AjaxResult.success;

@RestController
@RequestMapping("/merchant/info")
@Slf4j
public class MerchantInfoController {
    @Autowired
    private IMerchantService merchantService;

    @Autowired
    private IMerchantAuthService merchantAuthService;

    @Autowired
    private AliOssUtil aliOssUtil;

    @Autowired
    private MerchantProfileService merchantProfileService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private MerchantProfileService profileService;

    /** 获取个人信息（来源 sys_user） */
    @GetMapping("/personal-info")
    public AjaxResult personalInfo() {
        Long userId = SecurityUtils.getLoginUser().getUserId(); // 你们商家与 RuoYi 用户ID已绑定
        PersonalInfoVO vo = profileService.getPersonalInfo(userId);
        return AjaxResult.success("查询成功", vo);
    }

    /** 人：修改个人信息 -> sys_user */
    @PutMapping("/update-personal")
    public AjaxResult updatePersonal(@RequestBody @Validated UpdatePersonalInfoRequest req) {
        Long userId = SecurityUtils.getLoginUser().getUserId(); // 绑定 RuoYi 用户
        merchantProfileService.updatePersonalInfo(userId, req);
        return AjaxResult.success("修改成功");
    }

    /**
     * 获取用户详细信息
     * @return
     */
    @GetMapping
    public AjaxResult getInfo() {
        // 从token中获取商家ID
        Long merchantId = MerchantSecurityUtils.getMerchantId();

        // 查询商家详情
        MerchantDetailVO merchantInfo = merchantService.getMerchantInfo(merchantId);

        return success(merchantInfo);
    }

    /**
     * 上传个人头像（sys_user.avatar）
     */
    @PostMapping(value = "/upload-avatar", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public AjaxResult uploadUserAvatar(@RequestParam("file") MultipartFile file) {
        try {
            // 1. 获取当前登录用户ID（RuoYi 通用）
            Long userId = SecurityUtils.getLoginUser().getUserId();
            log.info("用户{}上传个人头像：{}", userId, file.getOriginalFilename());

            // 2. 基础校验
            if (file.isEmpty()) {
                return error("上传文件不能为空");
            }

            // 3. 类型校验：仅图片
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                return error("只允许上传图片文件");
            }

            // 4. 大小校验（5MB）
            long maxSize = 5 * 1024 * 1024;
            if (file.getSize() > maxSize) {
                return error("文件大小不能超过5MB");
            }

            // 5. 后缀名安全提取 + 白名单
            String originalFilename = file.getOriginalFilename();
            String suffixName = "";
            if (originalFilename != null && originalFilename.lastIndexOf('.') > -1) {
                suffixName = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
            }
            Set<String> allow = new HashSet<>(Arrays.asList(".jpg", ".jpeg", ".png", ".gif", ".webp"));
            if (!allow.contains(suffixName)) {
                return error("不支持的图片格式，仅支持：" + String.join(",", allow));
            }

            // 6. 生成对象名：user/{userId}/avatar/yyyy/MM/dd/{uuid}.ext
            LocalDateTime now = LocalDateTime.now();
            String datePath = now.format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
            String objectName = String.format("merchant_profile/%d/avatar/%s/%s%s",
                    userId, datePath, UUID.randomUUID(), suffixName);

            // 7. 上传到 OSS（复用你原来的工具类）
            String avatarUrl = aliOssUtil.upload(file.getBytes(), objectName);
            log.info("个人头像上传成功，URL: {}", avatarUrl);

            // 8. sys_user.avatar 长度校验（你的表 avatar varchar(255)）
            if (avatarUrl != null && avatarUrl.length() > 255) {
                return error("头像URL过长（>255），请检查存储域名或路径长度");
            }

            // 9. 更新 sys_user.avatar
            profileService.updateAvatar(userId, avatarUrl);

            // 10. 可选：刷新登录缓存，使前端立刻看到新头像
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (loginUser != null && loginUser.getUser() != null) {
                loginUser.getUser().setAvatar(avatarUrl);
                tokenService.setLoginUser(loginUser);
            }

            // 11. 返回
            return success("上传成功").put("avatarUrl", avatarUrl);

        } catch (IOException e) {
            log.error("个人头像上传失败", e);
            return error("文件上传失败：" + e.getMessage());
        }
    }

    /**
     * 上传商家店铺头像
     */
    @PostMapping("/upload-shopAvatar")
    public AjaxResult uploadAvatar(@RequestParam("file") MultipartFile file) {
        try {
            // 1. 获取当前登录商家ID
            Long merchantId = MerchantSecurityUtils.getMerchantId();
            log.info("商家{}上传头像：{}", merchantId, file.getOriginalFilename());

            // 2. 验证文件
            if (file.isEmpty()) {
                return error("上传文件不能为空");
            }

            // 3. 验证文件类型（只允许图片）
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                return error("只允许上传图片文件");
            }

            // 4. 验证文件大小（限制2MB，头像不需要太大）
            long maxSize = 2 * 1024 * 1024; // 2MB
            if (file.getSize() > maxSize) {
                return error("文件大小不能超过2MB");
            }

            // 5. 生成文件名
            String originalFilename = file.getOriginalFilename();
            String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));

            // 按日期和商家ID分类存储：merchant/商家ID/avatar/日期/文件名
            LocalDateTime now = LocalDateTime.now();
            String datePath = now.format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
            String objectName = String.format("merchant/%d/avatar/%s/%s%s",
                    merchantId, datePath, UUID.randomUUID(), suffixName);

            // 6. 上传到OSS
            String avatarUrl = aliOssUtil.upload(file.getBytes(), objectName);
            log.info("头像上传成功，URL: {}", avatarUrl);

            // 7. 更新商家表的avatarUrl字段
            merchantService.updateAvatar(merchantId, avatarUrl);

            // 8. 返回结果
            return success("上传成功")
                    .put("avatarUrl", avatarUrl);

        } catch (IOException e) {
            log.error("头像上传失败", e);
            return error("文件上传失败：" + e.getMessage());
        }
    }

    /**
     * 修改营业状态
     */
    @PutMapping("/status")
    public AjaxResult updateStatus(@Validated @RequestBody UpdateStatusRequest request) {
        // 参数校验
        request.validate();

        // 从token中获取商家ID
        Long merchantId = MerchantSecurityUtils.getMerchantId();

        // 更新状态
        UpdateStatusResponse response = merchantService.updateMerchantStatus(
                merchantId, request.getStatus());

        return success("状态更新成功", response);
    }

    /**
     * 修改登录密码
     */
    @PutMapping("/account/change-password")
    public AjaxResult changePassword(@Validated @RequestBody ChangePasswordDTO changePasswordDTO) {
        int rows = merchantAuthService.changePassword(changePasswordDTO);
        return rows > 0 ? AjaxResult.success("密码修改成功") : AjaxResult.error("密码修改失败");
    }

    /**
     * 忘记密码（通过手机验证码重置）
     */
    @PostMapping("/account/forgot-password")
    public AjaxResult forgotPassword(@Validated @RequestBody ForgotPasswordDTO forgotPasswordDTO) {
        int rows = merchantAuthService.forgotPassword(forgotPasswordDTO);
        return rows > 0 ? AjaxResult.success("密码重置成功，请使用新密码登录") : AjaxResult.error("密码重置失败");
    }

    /**
     * 注销账号
     */
    @DeleteMapping("/account/delete")
    public AjaxResult deleteAccount(@Validated @RequestBody DeleteAccountDTO deleteAccountDTO) {
        int rows = merchantAuthService.deleteAccount(deleteAccountDTO);
        return rows > 0 ? AjaxResult.success("账号注销成功") : AjaxResult.error("账号注销失败");
    }

    /**
     * 退出登录
     */
    @PostMapping("/account/logout")
    public AjaxResult logout() {
        boolean result = merchantAuthService.logout();
        return result ? AjaxResult.success("退出登录成功") : AjaxResult.error("退出登录失败");
    }

}
